package com.example.thread.d4lock锁;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Data
@NoArgsConstructor
public class Account {
    private String cardId;
    private double money;
    // 创建了一个锁对象
    private final Lock lk = new ReentrantLock();
    public Account(String cardId,double money) {
        this.cardId = cardId;
        this.money = money;
    }
    // 小明，小红同时来取钱
    public void drawMoney(double money) {
        // 先搞清楚谁来取钱
        String name = Thread.currentThread().getName();
        try {
            lk.lock();
            // 取钱
            if (this.money >= money) {
                System.out.println(name + "取钱：" + money + "成功");
                this.money -= money;
                System.out.println(name + "来取钱后，余额剩余：" + this.money);
            } else {
                System.out.println(name + "来取钱，余额不足！");
            }
        } finally {
            lk.unlock();
        }
    }
}
